package com.sx.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(filterName = "LoginFilter",urlPatterns = "/a")
public class LoginFilter implements Filter {
  public void destroy() {
  }

  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    resp.setContentType("text/html;charset=UTF-8");
    HttpServletRequest request=(HttpServletRequest)req;
    HttpServletResponse response=(HttpServletResponse) resp;

    String uri = request.getRequestURI();

    if (uri.contains("/login.jsp") || uri.contains("/loginServlet") || uri.contains("/css/*") || uri.contains("/fonts/*") || uri.contains("/js/*")) {
      chain.doFilter(req, resp);
    } else {
      String id = (String) request.getSession().getAttribute("username");
      if(id != null) {
        chain.doFilter(req, resp);
      } else {
        PrintWriter pw=resp.getWriter();
        pw.write("<script language='JavaScript'>alert('你没有权限访问，请登录!')</script>");
        response.setHeader("Refresh","1,/PlayerManagement_war_exploded/layuimini/jsp/login.jsp");
      }
    }
  }

  public void init(FilterConfig config) throws ServletException {

  }

}
